<?php


namespace app\lib;

use app\Code;
use app\lib\exception\AliyunApiException;
use app\lib\exception\ServiceException;
use app\lib\exception\WxApiException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use Throwable;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\ValidateException;
use think\Response;


class Http extends Handle
{
    protected function returnJson($msg, $code){
        return Response::create([
            'msg' => $msg,
            'code' => $code,
            'data' => [],
        ], 'json');
    }

    public function render($request, Throwable $e): Response
    {
        //id不存在
        if ($e instanceof ModelNotFoundException)
        {
            return $this->returnJson('THE ID DATA NotFound', Code::PARAM_EXCEPTION);
        }

        //验证器异常
        if ($e instanceof ValidateException)
        {
            return $this->returnJson($e->getMessage(), Code::PARAM_EXCEPTION);
        }

        //服务异常
        if ($e instanceof ServiceException)
        {
            return $this->returnJson($e->getMessage(), Code::SERVER_EXCEPTION);
        }

        //外部服务异常
        if ($e instanceof AliyunApiException)
        {
            return $this->returnJson('alyun '.$e->getMessage(), Code::OUTSIDE_API_EXCEPTION);
        }

        //外部服务异常
        if ($e instanceof WxApiException)
        {
            return $this->returnJson('wx '.$e->getMessage(), Code::OUTSIDE_API_EXCEPTION);
        }

        // 其他错误交给系统处理
        return parent::render($request, $e);
    }
}